// GuideManager.ts
import { _decorator, Component, director, resources, JsonAsset, instantiate, find ,Node, Prefab} from 'cc';
import { GuideEvent } from './GuideEvent';
const { ccclass } = _decorator;

@ccclass('GuideManager')
export class GuideManager extends Component {
    private currentStep: number = 0;
    private steps: any[] = [];

    onLoad() {
        this.initGuideRoot();
        this.loadConfig();
    }

    private initGuideRoot() {
        const guideRoot = new Node('GuideRoot');
        this.node.addChild(guideRoot);
        this.node = guideRoot;

        // 加载并实例化遮罩和对话框
        resources.load('guide/prefabs/GuideMask', (err, prefab) => {
            const maskNode =  instantiate(prefab as Prefab);
            guideRoot.addChild(maskNode);
        });

        resources.load('guide/prefabs/GuideDialog', (err, prefab) => {
            const dialogNode =  instantiate(prefab as Prefab);
            guideRoot.addChild(dialogNode);
            guideRoot.setSiblingIndex(9999)
        });
    }

    private loadConfig() {
        resources.load('guide/GuideStepConfig', JsonAsset, (err, asset) => {
            if (err) {
                console.error('引导配置加载失败:', err);
                return;
            }
            this.steps = asset!.json.steps;
        });
    }

    public startGuide() {
        this.currentStep = 0;
        this.executeStep(this.steps[0]);
    }

    private executeStep(step: any) {
        // 派发步骤开始事件
        director.emit(GuideEvent.STEP_START, step);

        console.log('遮罩是否显示',step.mask)
        if (step.mask) {
            const targetNode = find(step.targetNode);
            if (targetNode) {
                director.emit(GuideEvent.SHOW_MASK, targetNode, step.highlight);
            }
        }

        director.emit(GuideEvent.SHOW_DIALOG, step);

        this.registerTrigger(step);
    }

    private registerTrigger(step: any) {
        switch (step.trigger) {
            case 'node_click':
                const node = find(step.targetNode);
                if (node) {
                    node.once(Node.EventType.TOUCH_END, this.onTrigger, this);
                }
                break;
            case 'custom_event':
                director.once(step.eventName, this.onTrigger, this);
                break;
        }
    }

    private onTrigger(data?: any) {
        director.emit(GuideEvent.STEP_END);
        console.log('点击后触发')
        this.currentStep++;
        if (this.currentStep < this.steps.length) {
            this.executeStep(this.steps[this.currentStep]);
        } else {
            this.finishGuide();
        }
    }

    private finishGuide() {
        console.log('引导完成');
    }
}